package com.atguigu.project;

import com.atguigu.been.MarketingUserBehavior;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.RichSourceFunction;

import javax.lang.model.element.VariableElement;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

/**
 * @author wky
 * @create 2021-07-16-11:30
 */
public class Project_AppAnalysis_By_Chanel {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment senv = StreamExecutionEnvironment.getExecutionEnvironment();
        senv.setParallelism(1);
        //senv.setRuntimeMode(RuntimeExecutionMode.BATCH);
        DataStreamSource<MarketingUserBehavior> streamSource = senv.addSource(new MySource());
        SingleOutputStreamOperator<Tuple2<String, Long>> map = streamSource.map(new MapFunction<MarketingUserBehavior, Tuple2<String, Long>>() {
            @Override
            public Tuple2<String, Long> map(MarketingUserBehavior UserBehavior) throws Exception {
                return Tuple2.of(UserBehavior.getChannel() + "-" + UserBehavior.getBehavior(), 1L);
            }
        });
        KeyedStream<Tuple2<String, Long>, Tuple> tuple2TupleKeyedStream = map.keyBy(0);
        tuple2TupleKeyedStream.sum(1).print();
        senv.execute();


    }
    public static class MySource extends RichSourceFunction<MarketingUserBehavior>{
        Boolean bool = true ;
        Random random = new Random();
        List<String> channels = Arrays.asList("huawwei", "xiaomi", "apple", "baidu", "qq", "oppo", "vivo");
        List<String> behaviors = Arrays.asList("download", "install", "update", "uninstall");

        @Override
        public void run(SourceContext<MarketingUserBehavior> sourceContext) throws Exception {
           while (bool){
               MarketingUserBehavior userBehavior = new MarketingUserBehavior(
                       (long) (random.nextInt(10000)),
                       behaviors.get(random.nextInt(behaviors.size())),
                       channels.get(random.nextInt(channels.size())),
                       System.currentTimeMillis()
               );
               sourceContext.collect(userBehavior);
               Thread.sleep(100);
           }
        }

        @Override
        public void cancel() {
            bool = false;
        }
    }
}
